<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 微信支付相关接口处理
 */
class Controller_Pc_Api_V2_Wxpay extends Stourweb_Controller
{
    /**
     * @function 支付回调
     */
    public function action_notify()
    {
        $data = file_get_contents('php://input');
        require_once BASEPATH . 'plugins/api/vendor/weixin/lib/notify.php';
        require_once BASEPATH . 'plugins/api/vendor/weixin/lib/WxPay.Api.php';
        $notify = new notify();
        $res = $notify->FromXml($data);
        $this->NotifyProcess($res);
        $notify->Handle(true);
        $ip = $_SERVER['SERVER_ADDR'];
        $file_name = 'notify_'.$ip.'_'.date('Ymd').'.log';
        self::write_logs('notify', $data, $file_name);
    }

    /**
     * @function 支付回调进程
     * @param $data
     * @return bool
     */
    public function NotifyProcess($data)
    {
        $data['time_one'] = date('YmdHis',time());
        $data['time_two'] = time();
        $bool = false;
        //返回状态码、业务结果
        if (array_key_exists("return_code", $data) && array_key_exists("result_code", $data) && $data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS')
        {
            //查询订单
            if (isset($data["out_trade_no"]) && $data["out_trade_no"] != "")
            {
                $attach = explode('||',$data['attach']);
                $orderid = count($attach) >1 ? $attach[1] : $data['attach'];
                $total_fee = $data['total_fee']/100; //支付的金额
                $data['order_change']=false;
                if (isset($data['total_fee']) && self::confirm_order_price($orderid,$total_fee))
                {
                    $data['order_change']=true;
                    $bool = true;
                    $params = array(
                        'appid' => $data['appid'],
                        'mch_id' => $data['mch_id'],
                        'transaction_id' => $data['transaction_id'],
                        'out_trade_no'	=> $data['out_trade_no'],
                        'total_fee'	=> $data['total_fee'],
                        'orderid' => $orderid,
                        'mch_key' => DB::select()->from('sysconfig')->where("varname='cfg_wxpay_key'")->execute()->get('value'),
                        'source'=>'wxxcx'
                    );
                    self::pay_success($orderid,$params);
                }
            }
        }
        return $bool;
    }

    /**
     * @function 检测支付价格是否相同
     * @param $orderId
     * @param $payPrice
     * @return bool
     */
    public  function confirm_order_price($orderId,$payPrice)
    {
        $result = Model_Api_V2_Order::get_detail($orderId);
        $total_price = $result['totalprice'];
        if($result['iscoupon']['cmoney']){
            $total_price = bcsub($total_price,$result['iscoupon']['cmoney'],2);
        }
        if($result['jifentprice']){
            $total_price = bcsub($total_price,$result['jifentprice'],2);
        }
        if($result['platform_discount']){
            $total_price = bcsub($total_price,$result['platform_discount'],2);
        }
        if($result['envelope_price']){
            $total_price = bcsub($total_price,$result['envelope_price'],2);
        }
        if($result['together_deduct']){
            $total_price = bcsub($total_price,$result['together_deduct'],2);
        }

        $total_price = intval($total_price * 100);
        $payPrice = intval($payPrice * 100);
        self::write_logs('notify_process-支付回调进程金额', [$total_price,$payPrice,$result]);
        if($total_price == $payPrice)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * @function 支付成功
     * @param $orderId
     * @param $noData
     * @return bool
     */
    public  function pay_success($orderId,$noData)
    {
        $result = Model_Api_V2_Order::get_detail($orderId);
        if (isset($result['ordersn']) && !empty($result['ordersn'])) {
            if (!in_array($result['status'], array(1, 3))) {
                return false;
            }
            // 切换订单状态
            $ordersn = $result['ordersn'];
            St_Payment::change_order($ordersn, '微信小程序');

            //小程序支付状态
            $transaction_id = $noData['transaction_id'];
            $res = DB::select()->from('xcx_wxpay_data')
                ->where("transaction_id", "=", $transaction_id)
                ->and_where("orderid", "=", $orderId)
                ->execute()->current();
            if (!$res) {
                $data['appid'] = $noData['appid'];
                $data['mch_id'] = $noData['mch_id'];
                $data['transaction_id'] = $transaction_id;
                $out_trade_no = $noData['out_trade_no'];
                $data['out_trade_no'] = substr($out_trade_no, 0, -4); // 去掉支付时添加的4位随机数
                $data['total_fee'] = $noData['total_fee'];
                $data['orderid'] = $noData['orderid'];
                $data['mch_key'] = $noData['mch_key'];
                //数据入库
                DB::insert('xcx_wxpay_data', array_keys($data))->values(array_values($data))->execute();
                //更改支付数据
                $online_transaction_no = json_encode(array(
                    'source' => 'wxxcx',
                    'transaction_no' => $data['transaction_id']
                ));
                DB::update('member_order')->where('id', '=',
                    $data['orderid'])->set(array('online_transaction_no' => $online_transaction_no))->execute();
            }
        }
    }

    /**
     * @function 写日志
     * @param $flag
     * @param $filename
     * @param $value
     */
    private static function write_logs($flag,$value,$filename = '')
    {
        // 加入错误日志
        $filename = $filename ? $filename : date("Ymd").".txt";
        $logDir   = BASEPATH . "data/uniapp/logs/wxpay";
        $request_result['message'] = $logDir;
        if (!file_exists($logDir)) {
            mkdir($logDir, 0777, true);
        }
        $logPath = $logDir.'/'.$filename;
        $data = "=========================" . PHP_EOL;
        $data .= "time:".time(). PHP_EOL;
        $data .= "flag:{$flag}" . PHP_EOL;
        $data .= "err:{$value}" . PHP_EOL;
        file_put_contents($logPath, $data, FILE_APPEND);
    }

}